package com.jingran.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.jingran.cache.RedisCache;
import com.jingran.entity.UserEntity;
import com.jingran.mapper.UserMapper;
import com.jingran.utils.SpringRedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 测试代码类:单点登录
 * @author jingran
 */
@RestController
public class TestController extends BaseController{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    RedisCache redisCache;

    @Autowired
    SpringRedisUtils springRedisUtils;

    ConcurrentHashMap<Object, Object> map = new ConcurrentHashMap<>();
    /**
     * 登录功能
     * @param username 用户名
     * @param password 密码
     * @return 用户名和token
     */
    @CrossOrigin
    @RequestMapping("/login")
    public Object login(String username, String password, String code){
        if(!StringUtils.hasText(username) || !StringUtils.hasText(password) || !StringUtils.hasText(code)){
            return resultErrorParamsNull();
        }
//        String verifyCodeExpected = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
//        if(!verifyCodeExpected.equals(code)){
//            System.out.println("验证码错误");
//            return resultError();
//        }
        if (springRedisUtils.exists(code)) {
            springRedisUtils.delete(code);
        }else{
            return resultError();
        }
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper
                .eq("username",username)
                .eq("password",password);
        List<Object> objects = userMapper.selectObjs(wrapper);
        if (objects.isEmpty()){
            return resultError();
        }else {
            map.put("username",username);
            String token = UUID.randomUUID().toString().replace("-","");
            map.put("token", token);
            UserEntity userEntity = new UserEntity();
            userEntity.setUsername(username);
            userEntity.setPassword(password);
            redisCache.setSessionData(token, JSON.toJSONString(userEntity));
            return map;
        }
    }

    @Resource
    private Producer captchaProducer = null;

    /**
     * 验证码
     * @param request 请求
     * @param response 响应
     * @throws Exception 异常
     */
    @RequestMapping("/kaptcha")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ServletOutputStream out = null;
        try {
            HttpSession session = request.getSession();
            //设置页面不缓存
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            response.setContentType("image/jpeg");
            // 生成验证码编码
            String capText = captchaProducer.createText();
            //获取session，并将验证码编码存放到session中
            session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
            //这里没办法，只能用redis存验证码
            springRedisUtils.set(capText,capText,60);
            //向客户端写出
            // 将验证码编码生成图片
            BufferedImage bi = captchaProducer.createImage(capText);
            out = response.getOutputStream();
            ImageIO.write(bi, "jpg", out);
        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
